from flask import Blueprint, jsonify, request, send_file, current_app, session
from flask_login import login_required, current_user
import os
from datetime import datetime, timedelta
import tempfile
from werkzeug.security import check_password_hash, generate_password_hash

from app.data_processing.sentiment_analyzer import SentimentAnalyzer
from app.data_processing.hotspot_detector import HotspotDetector
from app.data_processing.trend_analyzer import TrendAnalyzer
from app.data_processing.location_analyzer import LocationAnalyzer
from app.data_processing.report_generator import (
    ReportGenerator,
    generate_daily_report,
    generate_weekly_report,
    generate_monthly_report,
    generate_custom_report
)
from app.data_collection.collector import DataCollector
from app.data_collection.news_crawler import NewsCrawler
from app.data_collection.weibo_crawler import WeiboCrawler
from app import db
from app.models import Article, SocialMediaPost, Keyword, SentimentHistory

# 创建 API 蓝图
api_blueprint = Blueprint('api', __name__)

# 初始化分析器
analyzer = SentimentAnalyzer(api_key=os.getenv('OPENAI_API_KEY'))
hotspot_detector = HotspotDetector()
trend_analyzer = TrendAnalyzer()
location_analyzer = LocationAnalyzer()
data_collector = DataCollector(api_key=os.getenv('OPENAI_API_KEY'))
news_crawler = NewsCrawler()
weibo_crawler = WeiboCrawler()

# 初始化报告生成器
report_generator = ReportGenerator()

@api_blueprint.route('/analyze', methods=['POST'])
def analyze_sentiment():
    data = request.get_json()
    text = data.get('text', '')
    # ... 处理逻辑 ...
    return jsonify({'result': 'success'})

@api_blueprint.route('/statistics')
@login_required
def get_statistics():
    """获取统计数据"""
    try:
        days = int(request.args.get('days', 30))
        
        # 获取时间范围
        start_date = datetime.now() - timedelta(days=days)
        
        # 获取文章总数
        total_articles = Article.query.filter(Article.collected_at >= start_date).count()
        total_posts = SocialMediaPost.query.filter(SocialMediaPost.collected_at >= start_date).count()
        
        # 获取情感分布
        positive_articles = Article.query.filter(
            Article.collected_at >= start_date,
            Article.sentiment == '正面'
        ).count()
        
        negative_articles = Article.query.filter(
            Article.collected_at >= start_date,
            Article.sentiment == '负面'
        ).count()
        
        neutral_articles = Article.query.filter(
            Article.collected_at >= start_date,
            Article.sentiment == '中性'
        ).count()
        
        positive_posts = SocialMediaPost.query.filter(
            SocialMediaPost.collected_at >= start_date,
            SocialMediaPost.sentiment == '正面'
        ).count()
        
        negative_posts = SocialMediaPost.query.filter(
            SocialMediaPost.collected_at >= start_date,
            SocialMediaPost.sentiment == '负面'
        ).count()
        
        neutral_posts = SocialMediaPost.query.filter(
            SocialMediaPost.collected_at >= start_date,
            SocialMediaPost.sentiment == '中性'
        ).count()
        
        # 获取热门关键词
        keywords = Keyword.query.order_by(Keyword.frequency.desc()).limit(10).all()
        top_keywords = [keyword.word for keyword in keywords]
        
        # 返回统计数据
        stats = {
            'total_articles': total_articles + total_posts,
            'positive_count': positive_articles + positive_posts,
            'negative_count': negative_articles + negative_posts,
            'neutral_count': neutral_articles + neutral_posts,
            'top_keywords': top_keywords
        }
        
        return jsonify(stats)
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@api_blueprint.route('/hot_topics')
@login_required
def get_hot_topics():
    """获取热点话题"""
    try:
        days = int(request.args.get('days', 3))
        
        # 获取热点话题
        hot_topics = hotspot_detector.detect_hot_topics(days=days)
        
        return jsonify({'topics': hot_topics})
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@api_blueprint.route('/volume_trend')
@login_required
def get_volume_trend():
    """获取声量趋势"""
    try:
        days = int(request.args.get('days', 30))
        interval = request.args.get('interval', 'day')
        
        # 获取声量趋势
        volume_data = trend_analyzer.analyze_volume_trend(days=days, interval=interval)
        
        return jsonify(volume_data)
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@api_blueprint.route('/sentiment_trend')
@login_required
def get_sentiment_trend():
    """获取情感趋势"""
    try:
        days = int(request.args.get('days', 30))
        
        # 获取情感趋势
        sentiment_data = trend_analyzer.analyze_sentiment_trend(days=days)
        
        return jsonify(sentiment_data)
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@api_blueprint.route('/location_distribution')
@login_required
def get_location_distribution():
    """获取地域分布"""
    try:
        days = int(request.args.get('days', 30))
        
        # 获取地域分布
        location_data = location_analyzer.analyze_location_distribution(days=days)
        
        # 获取地图数据
        map_data = location_analyzer.generate_map_data(days=days)
        
        # 合并数据
        result = {**location_data, **map_data}
        
        return jsonify(result)
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@api_blueprint.route('/source_distribution')
@login_required
def get_source_distribution():
    """获取媒体来源分布"""
    try:
        days = int(request.args.get('days', 30))
        
        # 获取媒体来源分布
        source_data = trend_analyzer.analyze_source_distribution(days=days)
        
        return jsonify(source_data)
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@api_blueprint.route('/keyword_trend')
@login_required
def get_keyword_trend():
    """获取关键词趋势"""
    try:
        keyword = request.args.get('keyword', '')
        days = int(request.args.get('days', 30))
        
        if not keyword:
            return jsonify({'error': '关键词不能为空'}), 400
        
        # 获取关键词趋势
        keyword_data = trend_analyzer.analyze_keyword_trend(keyword=keyword, days=days)
        
        return jsonify(keyword_data)
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@api_blueprint.route('/collect_news', methods=['POST'])
@login_required
def collect_news():
    """采集新闻数据"""
    try:
        data = request.get_json()
        source = data.get('source', 'sina')
        
        # 启动采集任务
        task_id = data_collector.start_collection_task('news', {'source': source})
        
        return jsonify({'task_id': task_id, 'status': 'started'})
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@api_blueprint.route('/collect_weibo', methods=['POST'])
@login_required
def collect_weibo():
    """采集微博数据"""
    try:
        data = request.get_json()
        keyword = data.get('keyword', '')
        
        if not keyword:
            return jsonify({'error': '关键词不能为空'}), 400
        
        # 启动采集任务
        task_id = data_collector.start_collection_task('weibo', {'keyword': keyword})
        
        return jsonify({'task_id': task_id, 'status': 'started'})
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@api_blueprint.route('/hot_news')
@login_required
def get_hot_news():
    """获取热门新闻"""
    try:
        # 获取热门新闻
        hot_news = news_crawler.get_hot_news()
        
        return jsonify({'news': hot_news})
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@api_blueprint.route('/hot_weibo')
@login_required
def get_hot_weibo():
    """获取微博热搜"""
    try:
        # 获取微博热搜
        hot_topics = weibo_crawler.get_hot_topics()
        
        return jsonify({'topics': hot_topics})
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@api_blueprint.route('/api/reports/daily', methods=['GET'])
def get_daily_report():
    date_str = request.args.get('date')
    if date_str:
        try:
            date = datetime.strptime(date_str, '%Y-%m-%d')
        except ValueError:
            return jsonify({'error': '日期格式无效'}), 400
    else:
        date = datetime.now()
    
    report = generate_daily_report(date)
    return jsonify(report)

@api_blueprint.route('/api/reports/weekly', methods=['GET'])
def get_weekly_report():
    start_date_str = request.args.get('start_date')
    if start_date_str:
        try:
            start_date = datetime.strptime(start_date_str, '%Y-%m-%d')
        except ValueError:
            return jsonify({'error': '日期格式无效'}), 400
    else:
        start_date = datetime.now() - timedelta(days=7)
    
    report = generate_weekly_report(start_date)
    return jsonify(report)

@api_blueprint.route('/api/reports/monthly', methods=['GET'])
def get_monthly_report():
    year = request.args.get('year', type=int)
    month = request.args.get('month', type=int)
    
    if not year or not month:
        now = datetime.now()
        year = now.year
        month = now.month
    
    report = generate_monthly_report(year, month)
    return jsonify(report)

@api_blueprint.route('/api/reports/custom', methods=['GET'])
def get_custom_report():
    start_date_str = request.args.get('start_date')
    end_date_str = request.args.get('end_date')
    report_type = request.args.get('type', 'custom')
    
    try:
        start_date = datetime.strptime(start_date_str, '%Y-%m-%d')
        end_date = datetime.strptime(end_date_str, '%Y-%m-%d')
    except (ValueError, TypeError):
        return jsonify({'error': '日期格式无效'}), 400
    
    report = generate_custom_report(start_date, end_date, report_type)
    return jsonify(report)

@api_blueprint.route('/api/charts/sentiment', methods=['GET'])
def get_sentiment_chart():
    generator = ReportGenerator()
    chart_data = generator.generate_sentiment_chart()
    return jsonify({'chart_data': chart_data})

@api_blueprint.route('/api/charts/trend', methods=['GET'])
def get_trend_chart():
    start_date_str = request.args.get('start_date')
    end_date_str = request.args.get('end_date')
    
    try:
        start_date = datetime.strptime(start_date_str, '%Y-%m-%d')
        end_date = datetime.strptime(end_date_str, '%Y-%m-%d')
    except (ValueError, TypeError):
        return jsonify({'error': '日期格式无效'}), 400
    
    generator = ReportGenerator()
    chart_data = generator.generate_trend_chart(start_date, end_date)
    return jsonify({'chart_data': chart_data})

# 数据统计API
@api_blueprint.route('/api/stats/overview', methods=['GET'])
def get_stats_overview():
    return jsonify({
        'total_articles': 395000,
        'today_analysis': 25450,
        'total_users': 13256,
        'alerts': 35
    })

@api_blueprint.route('/api/stats/topics', methods=['GET'])
def get_hot_topics_stats():
    return jsonify({
        'topics': [
            {'title': '热门话题1', 'value': 500, 'percentage': '28%'},
            {'title': '热门话题2', 'value': 300, 'percentage': '15%'},
            {'title': '热门话题3', 'value': 200, 'percentage': '10%'}
        ]
    })

@api_blueprint.route('/api/stats/regions', methods=['GET'])
def get_region_stats():
    return jsonify({
        'regions': [
            {'name': '北京', 'value': 1200},
            {'name': '上海', 'value': 1000},
            {'name': '广州', 'value': 800}
        ]
    })

@api_blueprint.route('/dashboard/data', methods=['GET'])
def get_dashboard_data():
    """获取仪表板所需的所有数据"""
    current_app.logger.info("用户请求仪表板数据")
    
    try:
        # 获取时间范围参数
        days = request.args.get('days', 30, type=int)
        current_app.logger.info(f"请求的时间范围: {days}天")
        
        # 生成日期列表
        dates = []
        for i in range(days):
            date = (datetime.now() - timedelta(days=days-i-1)).strftime('%m-%d')
            dates.append(date)
        
        # 生成模拟数据
        import random
        
        # 趋势数据
        total_data = [random.randint(100, 300) for _ in range(days)]
        positive_data = [int(total * random.uniform(0.5, 0.8)) for total in total_data]
        negative_data = [total - positive for total, positive in zip(total_data, positive_data)]
        
        # 情感分析数据
        sentiment_data = {
            'positive': sum(positive_data),
            'neutral': random.randint(50, 150),
            'negative': sum(negative_data)
        }
        
        # 热门话题
        topics = [
            {'title': '经济发展新动向', 'hot': random.randint(80, 100), 'sentiment': 'positive'},
            {'title': '科技创新政策解读', 'hot': random.randint(70, 95), 'sentiment': 'positive'},
            {'title': '环保问题引发关注', 'hot': random.randint(60, 90), 'sentiment': 'negative'},
            {'title': '教育改革新举措', 'hot': random.randint(50, 85), 'sentiment': 'neutral'},
            {'title': '医疗健康新进展', 'hot': random.randint(40, 80), 'sentiment': 'positive'}
        ]
        
        # 关键词云数据
        keywords = [
            {'name': '经济', 'value': random.randint(80, 100)},
            {'name': '科技', 'value': random.randint(70, 95)},
            {'name': '政策', 'value': random.randint(65, 90)},
            {'name': '创新', 'value': random.randint(60, 85)},
            {'name': '发展', 'value': random.randint(55, 80)},
            {'name': '数字化', 'value': random.randint(50, 75)},
            {'name': '转型', 'value': random.randint(45, 70)},
            {'name': '产业', 'value': random.randint(40, 65)},
            {'name': '金融', 'value': random.randint(35, 60)},
            {'name': '教育', 'value': random.randint(30, 55)},
            {'name': '医疗', 'value': random.randint(25, 50)},
            {'name': '环保', 'value': random.randint(20, 45)},
            {'name': '智能', 'value': random.randint(15, 40)},
            {'name': '制造', 'value': random.randint(10, 35)},
            {'name': '消费', 'value': random.randint(5, 30)}
        ]
        
        # 来源分布数据
        sources = [
            {'name': '微博', 'value': random.randint(30, 40)},
            {'name': '新闻网站', 'value': random.randint(20, 30)},
            {'name': '微信', 'value': random.randint(15, 25)},
            {'name': '论坛', 'value': random.randint(10, 20)},
            {'name': '其他', 'value': random.randint(5, 10)}
        ]
        
        # 地区分布数据
        provinces = ['北京', '上海', '广东', '江苏', '浙江', '山东', '河南', '四川', '湖北', '湖南',
                    '河北', '福建', '安徽', '辽宁', '陕西', '江西', '重庆', '天津', '云南', '广西',
                    '山西', '内蒙古', '吉林', '黑龙江', '贵州', '海南', '甘肃', '宁夏', '青海', '西藏']
        
        region_data = [{'name': province, 'value': random.randint(100, 1000)} for province in provinces]
        
        # 统计数据
        stats = {
            'total_comments': sum(total_data),
            'total_visits': random.randint(10000, 20000),
            'user_count': random.randint(1000, 2000),
            'alert_count': random.randint(10, 50)
        }
        
        # 组装返回数据
        response_data = {
            'dates': dates,
            'trend': {
                'total': total_data,
                'positive': positive_data,
                'negative': negative_data
            },
            'sentiment': sentiment_data,
            'topics': topics,
            'keywords': keywords,
            'sources': sources,
            'regions': region_data,
            'stats': stats
        }
        
        current_app.logger.info("仪表板数据生成成功")
        return jsonify(response_data)
    
    except Exception as e:
        current_app.logger.error(f"生成仪表板数据时出错: {str(e)}")
        return jsonify({'error': str(e)}), 500

@api_blueprint.route('/api/user/profile', methods=['GET', 'POST'])
def user_profile():
    if request.method == 'GET':
        user = session.get('user')
        if not user:
            return jsonify({'error': '未登录'}), 401
            
        return jsonify({
            'username': user['username'],
            'displayName': user['name'],
            'email': 'admin@example.com',  # 模拟数据
            'phone': '13800138000'  # 模拟数据
        })
    
    elif request.method == 'POST':
        data = request.get_json()
        # 这里应该更新数据库中的用户信息
        # 现在只是模拟成功
        return jsonify({'message': '更新成功'})

@api_blueprint.route('/api/user/password', methods=['POST'])
def change_password():
    data = request.get_json()
    current_password = data.get('currentPassword')
    new_password = data.get('newPassword')
    
    if not current_password or not new_password:
        return jsonify({'error': '密码不能为空'}), 400
    
    # 这里应该验证当前密码并更新数据库
    # 现在只是模拟成功
    return jsonify({'message': '密码修改成功'})

@api_blueprint.route('/api/settings', methods=['GET', 'POST'])
def system_settings():
    if request.method == 'GET':
        # 返回模拟的系统设置
        return jsonify({
            'basic': {
                'systemName': '舆情监控系统',
                'refreshInterval': '300',
                'language': 'zh'
            },
            'notification': {
                'emailEnabled': True,
                'smsEnabled': False,
                'levels': ['high', 'medium']
            },
            'data': {
                'retentionPeriod': '90',
                'autoBackup': True,
                'backupFrequency': 'weekly'
            }
        })
    
    elif request.method == 'POST':
        data = request.get_json()
        # 这里应该保存系统设置到数据库
        # 现在只是模拟成功
        return jsonify({'message': '设置保存成功'}) 